<template>
  <div>
    <h1>{{ id ? '编辑' : '新建' }}管理员</h1>
    <el-form label-width="100px">
      <el-form-item label="用户名">
        <el-input v-model="model.username"></el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input type="password" v-model="model.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      model: {},
    };
  },

  created() {
    this.id && this.fetch();
  },

  methods: {
    async save() {
      if (!this.model.username || !this.model.password) {
        this.$message({
          showClose: true,
          message: '用户名和密码不能为空',
        });
        return;
      }
      let res;
      let message = '';
      // 根据id的有无 判断是新增还是修改
      if (this.id) {
        res = await this.axios.put(`rest/admin_users/${this.id}`, this.model);
        message = '修改成功';
      } else {
        res = await this.axios.post('rest/admin_users', this.model);
        message = '添加 成功';
      }

      this.$message({
        showClose: true,
        message: message,
        type: 'success',
      });

      setTimeout(() => {
        this.$router.push('/adminUser/list');
      }, 500);
    },

    async fetch() {
      const res = await this.axios.get(`rest/admin_users/${this.id}`);
      this.model = res.data;
    },
  },
};
</script>
<style scoped></style>;
